package com.xmtlxx.web.controller.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.PropertyLogNode;
import com.xmtlxx.common.enums.PropertyLogType;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.tengbo.PushDatasUtil;
import com.xmtlxx.common.tengbo.vo.PropertyLogModelsVo;
import com.xmtlxx.common.tengbo.vo.SmartCabinetOutVo;
import com.xmtlxx.common.tengbo.vo.SmartCabinetPickProVo;
import com.xmtlxx.common.utils.DateUtils;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.*;
import com.xmtlxx.oms.domain.bo.TaskBo;
import com.xmtlxx.oms.domain.vo.TaskVo;
import com.xmtlxx.oms.mapper.*;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.tms.mapper.WaybillMapper;
import com.xmtlxx.web.controller.center.service.ICommonService;
import com.xmtlxx.web.controller.wms.service.IPickService;
import com.xmtlxx.wms.domain.*;
import com.xmtlxx.wms.domain.bo.*;
import com.xmtlxx.wms.domain.vo.*;
import com.xmtlxx.wms.mapper.*;
import com.xmtlxx.wms.service.IInventoryService;
import com.xmtlxx.wms.service.IStoreLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 挑拣任务Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PickServiceImpl implements IPickService {

    private final PickMapper baseMapper;

    private final PickDtlMapper pickDtlMapper;

    private final ExWarehouseMapper exWarehouseMapper;

    private final ExWarehouseDtlMapper exWarehouseDtlMapper;

    private final SysOssMapper sysOssMapper;

    private final PropertyMapper propertyMapper;

    private final OperatorLogMapper logMapper;

    private final IStoreLogService iStoreLogService;

    private final IInventoryService iInventoryService;

    private final PropertyLogMapper propertyLogMapper;

    private final BoxMapper boxMapper;

    private final StoreMapper storeMapper;

    private final PutDtlMapper putDtlMapper;

    private final PutTaskMapper putTaskMapper;

    private final CabinetGroupMapper cabinetGroupMapper;

    private final CabinetMapper cabinetMapper;

    private final LocatorMapper locatorMapper;

    private final BoxDeptMapper boxDeptMapper;

    private final SysDeptMapper deptMapper;

    private final StoreAreaMapper areaMapper;

    private final DealMapper dealMapper;

    private final DealDtlMapper dealDtlMapper;

    private final ICommonService commonService;

    private final TaskMapper taskMapper;

    private final WaybillMapper waybillMapper;

    /**
     * 查询挑拣任务
     *
     * @param id 挑拣任务主键
     * @return 挑拣任务
     */
    @Override
    public PickVo queryById(String id) {
        //return baseMapper.selectVoById(id);
        return baseMapper.selectPickVoByID(id);
    }

    @Override
    public List<PickVo> queryByTaskId(String id) {

        List<PickVo> vos = new ArrayList<>();
        TaskVo taskVo = taskMapper.selectVoById(id);
        switch (taskVo.getType()) {
            case "2":
                DealBo dealBo = new DealBo();
                dealBo.setTaskId(id);
                List<DealVo> dealVoList = dealMapper.selectDealList(dealBo);
                if (dealVoList != null && dealVoList.size() > 0) {
                    dealVoList.stream().forEach(item -> {
                        PickVo pickVo = baseMapper.queryPickVoByExWarehouseID(item.getId());
                        if (pickVo != null) {
                            PickDtlBo dtlBo = new PickDtlBo();
                            dtlBo.setPickId(pickVo.getId());
                            List<PickDtlVo> dtlVoList = pickDtlMapper.selectPickDtlList(dtlBo);
                            pickVo.setItems(dtlVoList);
                            vos.add(pickVo);
                        }

                    });
                }

                break;
            default:
                PickBo bo = new PickBo();
                bo.setTaskId(id);
                List<PickVo> pickVos = baseMapper.selectPickList(bo);
                if (pickVos != null && pickVos.size() > 0) {
                    pickVos.stream().forEach(item -> {
                        PickDtlBo dtlBo = new PickDtlBo();
                        dtlBo.setPickId(item.getId());
                        List<PickDtlVo> dtlVoList = pickDtlMapper.selectPickDtlList(dtlBo);
                        item.setItems(dtlVoList);
                    });
                    vos.addAll(pickVos);
                }
                break;
        }
        return vos;
    }

    /**
     * 查询挑拣任务列表
     *
     * @param bo 挑拣任务
     * @return 挑拣任务
     */
    @Override
    public TableDataInfo<PickVo> queryPageList(PickBo bo, PageQuery pageQuery) {
        // LambdaQueryWrapper<Pick> lqw = buildQueryWrapper(bo);
        // Page<PickVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<PickVo> result = baseMapper.selectPagePickList(pageQuery.build(), bo);
        if (result != null && result.getRecords() != null && result.getRecords().size() > 0) {
            for (PickVo vo : result.getRecords()) {
                if (vo.getPickNo().indexOf("C") != -1) {
                    PickDtlBo dtlBo = new PickDtlBo();
                    dtlBo.setPickId(vo.getId());
                    List<PickDtlVo> dtls = pickDtlMapper.selectPickDtlList(dtlBo);
                    if (dtls != null && dtls.size() > 0) {
                        vo.setProNo(dtls.get(0).getPno());
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询挑拣任务列表
     *
     * @param bo 挑拣任务
     * @return 挑拣任务
     */
    @Override
    public List<PickVo> queryList(PickBo bo) {
        // LambdaQueryWrapper<Pick> lqw = buildQueryWrapper(bo);
        // return baseMapper.selectVoList(lqw);
        return baseMapper.selectPickList(bo);
    }

    private LambdaQueryWrapper<Pick> buildQueryWrapper(PickBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Pick> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getWid()), Pick::getWid, bo.getWid());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreId()), Pick::getStoreId, bo.getStoreId());
        lqw.eq(bo.getDeptId() != null, Pick::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getPickNo()), Pick::getPickNo, bo.getPickNo());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Pick::getStatus, bo.getStatus());
        lqw.eq(bo.getOperator() != null, Pick::getOperator, bo.getOperator());
        lqw.between(params.get("beginFinishTime") != null && params.get("endFinishTime") != null,
                Pick::getFinishTime, params.get("beginFinishTime"), params.get("endFinishTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), Pick::getCreateBy, bo.getCreateBy());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
                Pick::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getUpdateBy()), Pick::getUpdateBy, bo.getUpdateBy());
        lqw.eq(bo.getUpdateTime() != null, Pick::getUpdateTime, bo.getUpdateTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAcceptUser()), Pick::getAcceptUser, bo.getAcceptUser());
        lqw.between(params.get("beginAcceptTime") != null && params.get("endAcceptTime") != null,
                Pick::getAcceptTime, params.get("beginAcceptTime"), params.get("endAcceptTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getAcceptStatus()), Pick::getAcceptStatus, bo.getAcceptStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Pick::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增挑拣任务
     *
     * @param bo 挑拣任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Pick insertByBo(PickBo bo) {

        Pick add = BeanUtil.toBean(bo, Pick.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        add.setAcceptStatus("0");
        if (StringUtils.isEmpty(bo.getWid()) && !StringUtils.isEmpty(bo.getExno())) {
            LambdaQueryWrapper<ExWarehouse> lqw = Wrappers.lambdaQuery();
            lqw.eq(ExWarehouse::getExno, bo.getExno());
            lqw.eq(ExWarehouse::getDelFlag, "0");
            ExWarehouse exWarehouse = exWarehouseMapper.selectOne(lqw);
            if (exWarehouse != null) {
                add.setWid(exWarehouse.getId());
            }
        }

        List<PickDtl> dtls = new ArrayList<>();
        Long nums = 0l;
//        if(bo.getItems() != null && bo.getItems().size() > 0){
//            for(PickDtlVo item : bo.getItems()){
//                PickDtl dtl = BeanUtil.toBean(item, PickDtl.class);
//                dtl.setId(IdUtil.simpleUUID());
//                dtl.setPickId(add.getId());
//                dtl.setDelFlag("0");
//                dtl.setNums(item.getNums() == null ? 1L : item.getNums());
//                dtls.add(dtl);
//                nums += dtl.getNums();
//            }
//        }
        List<PropertyLog> logs = new ArrayList<>();
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            dtls = bo.getItems().stream().map(item -> {
                PickDtl dtl = new PickDtl();
                BeanUtil.copyProperties(item, dtl, "id");
                dtl.setId(IdUtil.simpleUUID());
                dtl.setPickId(add.getId());
                dtl.setDelFlag("0");
                dtl.setStatus("0");

                if (item.getIsPwd()) {
                    if (StringUtils.isNotEmpty(item.getPassword())) {
                        InventoryBo inBo = new InventoryBo();
                        inBo.setPno(dtl.getPno());
                        inBo.setStatus("0");
                        List<InventoryVo> inventoryVoList = iInventoryService.queryList(inBo);
                        if (inventoryVoList != null && inventoryVoList.size() > 0) {
                            if (!item.getPassword().equals(inventoryVoList.get(0).getPassword())) {
                                throw new ServiceException("您输入的编号：" + dtl.getPno() + "的保管密码错误，请重新输入！");
                            }
                        }
                    } else {
                        throw new ServiceException("编号：" + dtl.getPno() + "的保管密码不能为空！");
                    }
                }

                if (item.getIsPutPwd()) {
                    if (StringUtils.isNotEmpty(item.getConfirmPwd())) {
                        InventoryBo inBo = new InventoryBo();
                        inBo.setPno(dtl.getPno());
                        inBo.setStatus("0");
                        List<InventoryVo> inventoryVoList = iInventoryService.queryList(inBo);
                        if (inventoryVoList != null && inventoryVoList.size() > 0) {
                            if (!item.getConfirmPwd().equals(inventoryVoList.get(0).getPutPassword())) {
                                throw new ServiceException("您输入的编号：" + dtl.getPno() + "的上架密码错误，请重新输入！");
                            }
                        }
                    } else {
                        throw new ServiceException("编号：" + dtl.getPno() + "的上架密码不能为空！");
                    }
                }

                return dtl;
            }).collect(Collectors.toList());

            //计算财物数量
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

            logs = dtls.stream().map(item -> {
                String logContent = "新增挑拣任务：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，上架说明：" + (StringUtils.isNotEmpty(add.getMemo()) ? add.getMemo() : "") + ")";
                return saveLog(item, add.getId(), add.getDeptId(), add.getStoreId(), "挑拣任务");
            }).collect(Collectors.toList());

        }
        if (logs != null && logs.size() > 0) {
            propertyLogMapper.insertBatch(logs);
            logs.forEach(item -> {
                PropertyLogModelsVo pushData = new PropertyLogModelsVo();
                pushData.setApi("proBase");
                pushData.setData(propertyLogMapper.selectPropertyLogVoByID(item.getId()));
                PushDatasUtil.pushPropertyDatas(pushData);
            });
        }
        if (dtls != null && dtls.size() > 0) {
            pickDtlMapper.insertBatch(dtls);
        }

        //设置箱号使用
        List<Box> boxList = new ArrayList<>();
        if (bo.getBoxList() != null && bo.getBoxList().size() > 0) {
            boxList = bo.getBoxList().stream().map(item -> {
                Box box = boxMapper.selectById(item.getId());
                box.setBoxNo(item.getBoxNo());
                box.setStatus("1");
                return box;
            }).collect(Collectors.toList());
        }
        boxMapper.insertOrUpdateBatch(boxList);

        add.setNums(nums);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            for (SysOss oss : bo.getOss()) {
                oss.setBuss("Pick");
                oss.setObjid(add.getId());
                sysOssMapper.updateById(oss);
            }
        }
        addOperatorLog(add.getId(), "wms", "挑拣");
        if (flag) {
            return add;
        }
        return null;
    }

    /**
     * 修改挑拣任务
     *
     * @param bo 挑拣任务
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Pick updateByBo(PickBo bo) {

        Pick update = BeanUtil.toBean(bo, Pick.class);
        ExWarehouseVo exWarehouseVo = exWarehouseMapper.selectExWarehouseVoByID(update.getWid());
        TaskVo taskVo = taskMapper.selectTaskVoByID(exWarehouseVo.getTaskId());
        validEntityBeforeSave(update);

        List<PickDtl> dtls = new ArrayList<>();
        List<PickDtl> dels = new ArrayList<>();
        Long nums = 0l;

        if (bo.getItems() != null && bo.getItems().size() > 0) {

            List<Box> boxes = new ArrayList<>();

            dtls = bo.getItems().stream().map(item -> {
                PickDtl dtl = pickDtlMapper.selectById(item.getId());
                if (dtl == null) {
                    dtl = new PickDtl();
                    BeanUtil.copyProperties(item, dtl, "id");
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setPickId(update.getId());
                    dtl.setDelFlag("0");
                    dtl.setStatus("0");
                } else {
                    BeanUtil.copyProperties(item, dtl);

                    //处理箱号
                    Box box = null;
                    if (StringUtils.isNotEmpty(dtl.getBoxNo())) {
                        box = boxMapper.selectOne(new LambdaQueryWrapper<Box>().eq(Box::getBoxNo, dtl.getBoxNo()));
                        if (box == null) {
                            box = new Box();
                            box.setId(IdUtil.simpleUUID());
                            box.setBoxNo(dtl.getBoxNo());
                            box.setDeptId(LoginHelper.getDeptId());
                            box.setCreateDept(LoginHelper.getDeptId());
                            box.setDelFlag("0");
                            box.setStatus("1");
                            boxMapper.insert(box);
                        }
                        //箱子所在部门与申请账号部门不一致时，变更箱子所在部门为当前账号部门
                        if (box.getDeptId() != null && (box.getDeptId() != LoginHelper.getDeptId())) {
                            box.setDeptId(LoginHelper.getDeptId());
                        }
                        if (box.getStatus().equals("0")) {
                            //设置为已使用
                            box.setStatus("1");
                        }
                        boxMapper.insertOrUpdate(box);
                    }

                    if (box != null) {
                        dtl.setBoxId(box.getId());
                        if (!boxes.contains(box)) {
                            boxes.add(box);
                        }
                    }
                }

                return dtl;
            }).collect(Collectors.toList());

            //计算财物数量
            nums = dtls.stream().mapToLong(item -> item.getNums()).sum();

            //箱子使用记录
            if (boxes != null && boxes.size() > 0) {
                for (Box box : boxes) {
                    BoxDept boxDept = new BoxDept();
                    boxDept.setId(IdUtil.simpleUUID());
                    boxDept.setBoxId(box.getId());
                    boxDept.setBoxNo(box.getBoxNo());
                    boxDept.setBoxDept(box.getDeptId());
                    boxDept.setStatus("1");
                    boxDept.setDelFlag("0");
                    boxDeptMapper.insert(boxDept);
                }
            }

        }
        update.setNums(nums);
        if (dtls != null && dtls.size() > 0) {
            pickDtlMapper.insertOrUpdateBatch(dtls);
        }
        if (dels != null && dels.size() > 0) {
            pickDtlMapper.deleteBatchIds(dels);
        }


        if (bo.getOss() != null && bo.getOss().size() > 0) {
            for (SysOss oss : bo.getOss()) {
                oss.setBuss("Pick");
                oss.setObjid(update.getId());
                sysOssMapper.updateById(oss);
            }
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag && update.getStatus().equals("1") && update.getPickType().equals("1")) {//完成挑拣 生成库存记录及入库日志
            for (PickDtl dtl : dtls) {
                //生成库存
                InventoryBo inBo = new InventoryBo();
                inBo.setStoreId(dtl.getStoreId());
                inBo.setAreaId(dtl.getAreaId());
                inBo.setLocatorId(dtl.getLocatorId());
                inBo.setPno(dtl.getPno());
                inBo.setName(dtl.getName());
                inBo.setNums(dtl.getNums());
                inBo.setDeptId(update.getDeptId());
                inBo.setPics(dtl.getPics());
                inBo.setDelFlag("0");
                inBo.setTaskId(update.getId());
                inBo.setMark("1");
                inBo.setEvidence(taskVo.getEvidence());
                inBo.setTid(taskVo.getId());
                iInventoryService.addInventory(inBo);

                //生成仓库日志  0-入库；1-出库 2-处置 3-上架 4-挑拣 5-看样
                StoreLogBo logBo = new StoreLogBo();
                logBo.setDeptId(update.getDeptId());
                logBo.setStoreId(dtl.getStoreId());
                logBo.setLogTime(new Date());
                logBo.setUserId(LoginHelper.getUserId());
                logBo.setOperator(LoginHelper.getUsername());
                logBo.setLogType("4");
                logBo.setDelFlag("0");
                logBo.setContent(JsonUtils.toJsonString(bo));
                iStoreLogService.insertByBo(logBo);

                PropertyLog propertyLog = saveLog(dtl, update.getId(), update.getDeptId(), update.getStoreId(), "完成挑拣");
                propertyLogMapper.insert(propertyLog);
                PropertyLogModelsVo pushData = new PropertyLogModelsVo();
                pushData.setApi("proBase");
                pushData.setData(propertyLogMapper.selectPropertyLogVoByID(propertyLog.getId()));
                PushDatasUtil.pushPropertyDatas(pushData);

                //完成挑拣
                dtl.setStatus("1");
                pickDtlMapper.insertOrUpdate(dtl);
            }

            /**
             * 更新完成时间
             */
            if (update.getOperator() == null) {
                update.setOperator(LoginHelper.getUserId());
            }
            update.setFinishTime(new Date());
            baseMapper.updateById(update);

            //更新入库单上架状态
            ExWarehouse exWarehouse = exWarehouseMapper.selectById(update.getWid());
            if (exWarehouse != null) {
                exWarehouse.setIsFinish("1");//完成挑拣
                exWarehouseMapper.updateById(exWarehouse);
            }

            Deal deal = dealMapper.selectById(update.getWid());
            if (deal != null) {
                deal.setStatus("1");//完成挑拣
                dealMapper.updateById(deal);
            }

            addOperatorLog(StringUtils.isNotEmpty(exWarehouseVo.getTaskId()) ? exWarehouseVo.getTaskId() : exWarehouseVo.getId(), "wms", "完成挑拣");

        }
        if (flag) {
            return update;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Pick updateTaksByBo(PickBo bo) {

        Pick update = BeanUtil.toBean(bo, Pick.class);
        validEntityBeforeSave(update);
        TaskVo taskVo = null;
        ExWarehouseVo exWarehouseVo = exWarehouseMapper.selectExWarehouseVoByID(update.getWid());
        if (exWarehouseVo != null) {
            taskVo = taskMapper.selectTaskVoByID(exWarehouseVo.getTaskId());
        }
        DealVo dealVo = dealMapper.selectDealVoByID(update.getWid());
        if (dealVo != null) {
            taskVo = taskMapper.selectTaskVoByID(dealVo.getTaskId());

            exWarehouseVo = exWarehouseMapper.selectExWarehouseVoByTaskId(dealVo.getTaskId());

        }


        List<PickDtl> dtls = pickDtlMapper.selectList(new LambdaQueryWrapper<PickDtl>().eq(PickDtl::getPickId, update.getId()));

        //完成挑拣
        if (update.getStatus().equals("1")) {
            TaskVo finalTaskVo = taskVo;
            dtls.stream().forEach(item -> {
                item.setStatus("1");

                //减库存
                InventoryBo inBo = new InventoryBo();
                inBo.setPickType(bo.getPickType());
                inBo.setStoreId(item.getStoreId());
                inBo.setAreaId(item.getAreaId());
                inBo.setLocatorId(item.getLocatorId());
                inBo.setPno(item.getPno());
                inBo.setName(item.getName());
                inBo.setNums(item.getNums());
                inBo.setDeptId(update.getDeptId());
                inBo.setPics(item.getPics());
                inBo.setDelFlag("0");
                inBo.setTaskId(update.getId());
                inBo.setMark("1");
                inBo.setEvidence(finalTaskVo.getEvidence());
                iInventoryService.addInventory(inBo);

                /**
                 * 处理处置挑拣
                 */
                if (finalTaskVo != null && finalTaskVo.getType().equals("2")) {
                    Deal deal = dealMapper.selectDealVoByNo(item.getPno(), finalTaskVo.getId());
                    if (deal != null) {
                        deal.setIsFinish("1");
                        if (finalTaskVo.getIsTrailer().equals("1")) {//授权处理
                            deal.setStatus("1");
                            Task updateEnty = new Task();
                            updateEnty.setStatus("1");
                            updateEnty.setFinishTime(new Date());
                            taskMapper.update(updateEnty, new LambdaQueryWrapper<Task>().eq(Task::getId, finalTaskVo.getId()));
                        }
                        DealDtl dtl = dealDtlMapper.selectOne(new LambdaQueryWrapper<DealDtl>().eq(DealDtl::getDealId, deal.getId()));
                        if (dtl != null) {
                            dtl.setStatus("1");
                            dealDtlMapper.updateById(dtl);
                        }
                        dealMapper.updateById(deal);
                    }
                }

                String logContent = "完成挑拣任务：(物品编号：" + item.getPno() + "，物品名称：" + item.getName() + "，挑拣说明：" + (StringUtils.isNotEmpty(update.getMemo()) ? update.getMemo() : "") + ")";
                String info = JsonUtils.toJsonString(item);
                commonService.savePropertyLog(item.getPno(), update.getId(), item.getName(), PropertyLogType.PICK.getCode(), logContent, update.getDeptId(), info, item.getStoreId(), item.getNums(), null);
            });
            if (update.getOperator() == null) {
                update.setOperator(LoginHelper.getUserId());
            }
            update.setFinishTime(new Date());
            pickDtlMapper.updateBatchById(dtls);

            /**
             * 变更库位状态
             * 出库、处置后，变更库位状态
             */
            if (bo.getPickType().equals("0") || bo.getPickType().equals("2")) {
                List<String> locatorIds = new ArrayList<>();
                dtls.stream().forEach(item -> {
                    if (!locatorIds.contains(item.getLocatorId())) {
                        locatorIds.add(item.getLocatorId());
                    }
                });

                if (locatorIds.size() > 0) {
                    locatorIds.stream().forEach(id -> {
                        Locator locator = locatorMapper.selectById(id);
                        InventoryBo iBo = new InventoryBo();
                        iBo.setStatus("0");
                        iBo.setLocatorId(id);
                        List<InventoryVo> inventoryVos = iInventoryService.queryList(iBo);
                        //挑拣后，库位状态变更为已使用
                        if (inventoryVos != null && inventoryVos.size() > 0) {
                            locator.setStatus("1");
                        } else {
                            locator.setStatus("0");
                        }
                        locatorMapper.updateById(locator);
                    });
                }
            }


            //更新入库单上架状态
//            ExWarehouse exWarehouse = exWarehouseMapper.selectById(update.getWid());
            ExWarehouse exWarehouse = new ExWarehouse();
            BeanUtil.copyProperties(exWarehouseVo, exWarehouse);
            if (exWarehouse != null) {
                exWarehouse.setIsFinish("1");//完成挑拣

//                if(taskVo != null && taskVo.getType().equals("2") && taskVo.getIsTrailer().equals("1")){
//                    exWarehouse.setIsSign("1");//完成签收
//
//                    Task task = new Task();
//                    BeanUtil.copyProperties(taskVo,task);
//                    task.setStatus("1");//完成出库
//                    taskMapper.updateById(task);
//                }

                exWarehouseMapper.updateById(exWarehouse);

                List<ExWarehouseDtl> dtlList = exWarehouseDtlMapper.selectList(new LambdaQueryWrapper<ExWarehouseDtl>().eq(ExWarehouseDtl::getWid, exWarehouse.getId()));
                if (dtlList != null && dtlList.size() > 0) {
                    dtlList.stream().forEach(dtl -> {
                        dtl.setStatus("1");//已出库
                        exWarehouseDtlMapper.updateById(dtl);
                    });
                }
            }
            Deal deal = dealMapper.selectById(update.getWid());
            if (deal != null) {
                deal.setIsFinish("1");//完成挑拣
                if (taskVo != null && taskVo.getType().equals("2") && taskVo.getIsTrailer().equals("1")) {
                    deal.setIsSign("1");//完成签收
                }
                dealMapper.updateById(deal);
            }
            //生成仓库日志  0-入库；1-出库 2-处置 3-上架 4-挑拣 5-看样
            if (taskVo != null) {
                TaskBo taskBo = new TaskBo();
                BeanUtil.copyProperties(taskVo, taskBo);
                taskBo.setType("4");
                commonService.saveStoreLog(taskBo);
            }

            if (exWarehouseVo != null) {
                commonService.saveOperatorLog(StringUtils.isNotEmpty(exWarehouseVo.getTaskId()) ? exWarehouseVo.getTaskId() : exWarehouseVo.getId(), "wms", "完成挑拣");
            }
            if (dealVo != null) {
                commonService.saveOperatorLog(StringUtils.isNotEmpty(dealVo.getTaskId()) ? dealVo.getTaskId() : dealVo.getId(), "wms", "完成挑拣");
            }

        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            return update;
        }
        return null;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Pick entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除挑拣任务
     *
     * @param ids 需要删除的挑拣任务主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public PickVo pickVoByExWarehouse(String exWarehouseId) {

        PickVo vo = null;
        if (StringUtils.isNotEmpty(exWarehouseId)) {
            vo = baseMapper.queryPickVoByExWarehouseID(exWarehouseId);

            ExWarehouseVo exWarehouseVo = exWarehouseMapper.selectExWarehouseVoByID(exWarehouseId);

            ExWarehouseDtlBo exWarehouseDtlBo = new ExWarehouseDtlBo();
            exWarehouseDtlBo.setWid(exWarehouseId);
            List<ExWarehouseDtlVo> exWarehouseDtls = exWarehouseDtlMapper.selectExWarehouseDtlList(exWarehouseDtlBo);
            if (vo == null) {
                vo = new PickVo();
//                Pick pick = new Pick();
//                pick.setId(IdUtil.simpleUUID());
                vo.setWid(exWarehouseId);
                vo.setStoreId(exWarehouseVo.getStoreId());
                vo.setDeptId(LoginHelper.getDeptId());
                vo.setPickNo(exWarehouseVo.getTaskNo());
                vo.setStatus("0");
                vo.setDelFlag("0");
                vo.setPickType("1");//0-不删减 1-删减
//                pick.setOperator(LoginHelper.getUserId());

                List<PickDtlVo> pickDtlVos = exWarehouseDtls.stream().map(item -> {
                    PickDtlVo dtlVo = new PickDtlVo();
                    BeanUtil.copyProperties(item, dtlVo, "id");
//                    dtlVo.setId(IdUtil.simpleUUID());
                    dtlVo.setStatus("0");
                    dtlVo.setDelFlag("0");
//                    dtlVo.setPickId(pick.getId());
//                    dtlVo.setStoreId(pick.getStoreId());
                    dtlVo.setAreaId(locatorMapper.selectLocatorVoByID(item.getLocatorId()).getAreaId());
                    LocatorVo locatorVo = locatorMapper.selectLocatorVoByID(item.getLocatorId());
                    dtlVo.setLocatorId(item.getLocatorId());
                    dtlVo.setStoreName(storeMapper.selectVoById(dtlVo.getStoreId()).getName());
                    dtlVo.setLocatorName(locatorVo.getName());
                    dtlVo.setAreaName(locatorVo.getAreaName());

                    InventoryBo inBo = new InventoryBo();
                    inBo.setPno(dtlVo.getPno());
                    inBo.setStatus("0");
                    List<InventoryVo> inventoryVoList = iInventoryService.queryList(inBo);
                    if (inventoryVoList != null && inventoryVoList.size() > 0) {
                        if (StringUtils.isNotEmpty(inventoryVoList.get(0).getPassword())) {
                            dtlVo.setIsPwd(true);
                        } else {
                            dtlVo.setIsPwd(false);
                        }
                        if (StringUtils.isNotEmpty(inventoryVoList.get(0).getPutPassword())) {
                            dtlVo.setIsPutPwd(true);
                        } else {
                            dtlVo.setIsPutPwd(false);
                        }
                    } else {
                        dtlVo.setIsPwd(false);
                        dtlVo.setIsPutPwd(false);
                    }
                    return dtlVo;
                }).collect(Collectors.toList());

                vo.setItems(pickDtlVos);

                //设置挑拣总数
                Long nums = pickDtlVos.stream().mapToLong(item -> item.getNums()).sum();
                vo.setNums(nums);

//                baseMapper.insert(pick);

//                BeanUtil.copyProperties(pick,vo);

                List<PickDtl> dtls = pickDtlVos.stream().map(item -> {
                    PickDtl dtl = new PickDtl();
                    BeanUtil.copyProperties(item, dtl);
                    return dtl;
                }).collect(Collectors.toList());
                vo.setItems(pickDtlVos);
//                pickDtlMapper.insertBatch(dtls);
            } else {
                PickDtlBo pickDtlBo = new PickDtlBo();
                pickDtlBo.setPickId(vo.getId());
                List<PickDtlVo> pickDtlVos = pickDtlMapper.selectPickDtlList(pickDtlBo);
                vo.setItems(pickDtlVos);
            }

        } else {

        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickVo initBeanPickVo(String exWarehouseId) {

        String[] ignoreProperties = {"id", "createBy", "createTime", "updateBy", "updateTime"};
        PickVo vo = null;
        List<PickDtl> dtls = new ArrayList<>();
        List<PickDtlVo> dtlVoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(exWarehouseId)) {
            ExWarehouseVo exWarehouseVo = exWarehouseMapper.selectExWarehouseVoByID(exWarehouseId);
            ExWarehouseDtlBo edtlBo = new ExWarehouseDtlBo();
            edtlBo.setWid(exWarehouseId);
            List<ExWarehouseDtlVo> dtlVos = exWarehouseDtlMapper.selectExWarehouseDtlList(edtlBo);
            vo = baseMapper.queryPickVoByExWarehouseID(exWarehouseId);
            String areaId = null;
            if (vo == null) {
                vo = new PickVo();
                Pick add = new Pick();
                add.setWid(exWarehouseId);
                add.setStoreId(exWarehouseVo.getStoreId());
                add.setDeptId(LoginHelper.getDeptId());
                add.setPickNo(exWarehouseVo.getTaskNo());
                add.setStatus("0");
                add.setDelFlag("0");
                add.setId(IdUtil.simpleUUID());
                if (exWarehouseVo.getType().equals("1")) {
                    add.setPickType("0");
                }
                if (exWarehouseVo.getType().equals("3")) {
                    add.setPickType("1");
                }
                if (exWarehouseVo.getType().equals("2")) {
                    add.setPickType("2");
                }


                dtls = dtlVos.stream().map(item -> {
                    PickDtl dtl = new PickDtl();
                    BeanUtil.copyProperties(item, dtl, ignoreProperties);

                    InventoryVo inventory = iInventoryService.queryByPno(dtl.getPno(), add.getStoreId(), "0");

                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setDelFlag("0");
                    dtl.setStatus("0");
                    dtl.setLocatorId(inventory.getLocatorId());
                    dtl.setStoreId(add.getStoreId());
                    dtl.setAreaId(inventory.getAreaId());
                    dtl.setPickId(add.getId());
                    return dtl;
                }).collect(Collectors.toList());

                //设置挑拣总数
                Long nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
                add.setNums(nums);

                baseMapper.insert(add);
                pickDtlMapper.insertBatch(dtls);

                BeanUtil.copyProperties(add, vo);
                PickDtlBo dtlBo = new PickDtlBo();
                dtlBo.setPickId(vo.getId());
                vo.setItems(pickDtlMapper.selectPickDtlList(dtlBo));
            } else {
                PickDtlBo dtlBo = new PickDtlBo();
                dtlBo.setPickId(vo.getId());
                List<PickDtlVo> pickDtls = pickDtlMapper.selectPickDtlList(dtlBo);
                if (pickDtls == null || pickDtls.size() == 0) {
                    PickVo finalVo = vo;
                    dtls = dtlVos.stream().map(item -> {
                        PickDtl dtl = new PickDtl();
                        BeanUtil.copyProperties(item, dtl, ignoreProperties);

                        InventoryVo inventory = iInventoryService.queryByPno(dtl.getPno(), finalVo.getStoreId(), "0");

                        dtl.setId(IdUtil.simpleUUID());
                        dtl.setDelFlag("0");
                        dtl.setStatus("0");
                        dtl.setLocatorId(inventory.getLocatorId());
                        dtl.setStoreId(finalVo.getStoreId());
                        dtl.setAreaId(inventory.getAreaId());
                        dtl.setPickId(finalVo.getId());
                        return dtl;
                    }).collect(Collectors.toList());
                    boolean flag = pickDtlMapper.insertBatch(dtls);
                    if (flag) {
                        vo.setItems(pickDtlMapper.selectPickDtlList(dtlBo));
                    }
                } else {
                    vo.setItems(pickDtlMapper.selectPickDtlList(dtlBo));
                }

            }
        }
        return vo;
    }

    @Override
    public PickVo pickVoByDeal(String dealId) {

        PickVo vo = null;
        if (StringUtils.isNotEmpty(dealId)) {
            vo = baseMapper.queryPickVoByExWarehouseID(dealId);

            DealVo dealVo = dealMapper.selectDealVoByID(dealId);

            DealDtlBo dealDtlBo = new DealDtlBo();
            dealDtlBo.setDealId(dealId);
            List<DealDtlVo> dealDtlVos = dealDtlMapper.selectDealDtlList(dealDtlBo);
            if (vo == null) {
                vo = new PickVo();
//                Pick pick = new Pick();
//                pick.setId(IdUtil.simpleUUID());
                vo.setWid(dealId);
                vo.setStoreId(dealVo.getStoreId());
                vo.setDeptId(LoginHelper.getDeptId());
                vo.setPickNo(StringUtils.isNotEmpty(dealVo.getTaskNo()) ? dealVo.getTaskNo() : getNo());
                vo.setStatus("0");
                vo.setDelFlag("0");
                vo.setPickType("0");//0-不删减 1-删减
//                pick.setOperator(LoginHelper.getUserId());

                List<PickDtlVo> pickDtlVos = dealDtlVos.stream().map(item -> {
                    PickDtlVo dtlVo = new PickDtlVo();
                    BeanUtil.copyProperties(item, dtlVo, "id");
//                    dtlVo.setId(IdUtil.simpleUUID());
                    dtlVo.setStatus("0");
                    dtlVo.setDelFlag("0");
//                    dtlVo.setPickId(pick.getId());
//                    dtlVo.setStoreId(pick.getStoreId());
                    dtlVo.setAreaId(locatorMapper.selectLocatorVoByID(item.getLocatorId()).getAreaId());
                    LocatorVo locatorVo = locatorMapper.selectLocatorVoByID(item.getLocatorId());
                    dtlVo.setLocatorId(item.getLocatorId());
                    dtlVo.setStoreName(storeMapper.selectVoById(dtlVo.getStoreId()).getName());
                    dtlVo.setLocatorName(locatorVo.getName());
                    dtlVo.setAreaName(locatorVo.getAreaName());

                    InventoryBo inBo = new InventoryBo();
                    inBo.setPno(dtlVo.getPno());
                    inBo.setStatus("0");
                    List<InventoryVo> inventoryVoList = iInventoryService.queryList(inBo);
                    if (inventoryVoList != null && inventoryVoList.size() > 0) {
                        if (StringUtils.isNotEmpty(inventoryVoList.get(0).getPassword())) {
                            dtlVo.setIsPwd(true);
                        } else {
                            dtlVo.setIsPwd(false);
                        }

                        if (StringUtils.isNotEmpty(inventoryVoList.get(0).getPutPassword())) {
                            dtlVo.setIsPutPwd(true);
                        } else {
                            dtlVo.setIsPutPwd(false);
                        }
                    } else {
                        dtlVo.setIsPutPwd(false);
                    }
                    return dtlVo;
                }).collect(Collectors.toList());

                vo.setItems(pickDtlVos);

                //设置挑拣总数
                Long nums = pickDtlVos.stream().mapToLong(item -> item.getNums()).sum();
                vo.setNums(nums);

//                baseMapper.insert(pick);

//                BeanUtil.copyProperties(pick,vo);

                List<PickDtl> dtls = pickDtlVos.stream().map(item -> {
                    PickDtl dtl = new PickDtl();
                    BeanUtil.copyProperties(item, dtl);
                    return dtl;
                }).collect(Collectors.toList());
                vo.setItems(pickDtlVos);
//                pickDtlMapper.insertBatch(dtls);
            } else {
                PickDtlBo pickDtlBo = new PickDtlBo();
                pickDtlBo.setPickId(vo.getId());
                List<PickDtlVo> pickDtlVos = pickDtlMapper.selectPickDtlList(pickDtlBo);
                vo.setItems(pickDtlVos);
            }

        } else {

        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickVo initBeanDealPickVo(String dealId) {

        String[] ignoreProperties = {"id", "createBy", "createTime", "updateBy", "updateTime"};
        PickVo vo = null;
        List<PickDtl> dtls = new ArrayList<>();
        List<PickDtlVo> dtlVoList = new ArrayList<>();
        if (StringUtils.isNotEmpty(dealId)) {
            DealVo dealVo = dealMapper.selectDealVoByID(dealId);
            DealDtlBo edtlBo = new DealDtlBo();
            edtlBo.setDealId(dealId);
            List<DealDtlVo> dtlVos = dealDtlMapper.selectDealDtlList(edtlBo);
            vo = baseMapper.queryPickVoByExWarehouseID(dealId);
            String areaId = null;
            if (vo == null) {
                vo = new PickVo();
                Pick add = new Pick();
                add.setWid(dealId);
                add.setStoreId(dealVo.getStoreId());
                add.setDeptId(LoginHelper.getDeptId());
                add.setPickNo(StringUtils.isNotEmpty(dealVo.getTaskNo()) ? dealVo.getTaskNo() : getNo());
                add.setStatus("0");
                add.setDelFlag("0");
                add.setId(IdUtil.simpleUUID());
                //0-出库 1-调用 2-处置
                add.setPickType("2");

                dtls = dtlVos.stream().map(item -> {
                    PickDtl dtl = new PickDtl();
                    BeanUtil.copyProperties(item, dtl, ignoreProperties);
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setDelFlag("0");
                    dtl.setStatus("0");
                    Locator locator = locatorMapper.selectById(dtl.getLocatorId());
                    dtl.setAreaId(locator.getAreaId());
                    dtl.setPickId(add.getId());
                    return dtl;
                }).collect(Collectors.toList());

                //设置挑拣总数
                Long nums = dtls.stream().mapToLong(item -> item.getNums()).sum();
                add.setNums(nums);

                baseMapper.insert(add);
                pickDtlMapper.insertBatch(dtls);

                BeanUtil.copyProperties(add, vo);
                PickDtlBo dtlBo = new PickDtlBo();
                dtlBo.setPickId(vo.getId());
                vo.setItems(pickDtlMapper.selectPickDtlList(dtlBo));
            } else {
                PickDtlBo dtlBo = new PickDtlBo();
                dtlBo.setPickId(vo.getId());
                vo.setItems(pickDtlMapper.selectPickDtlList(dtlBo));
            }
        }
        return vo;
    }

    @Override
    public Boolean syncUpdateBatchOutSmartCabinet(SmartCabinetOutVo data) {

        Boolean flag = false;
        //
        if (data != null && StringUtils.isNotBlank(data.getProId())) {
            String[] proIds = data.getProId().split(",");
            for (String id : proIds) {
                //根据上架任务单ID 获取财物、库位信息 匹配是否有相应的挑拣任务
                PutDtl putDtl = putDtlMapper.selectById(id);
                List<PickDtl> dtls = pickDtlMapper.selectList(new LambdaQueryWrapper<PickDtl>()
                        .eq(PickDtl::getStoreId, putDtl.getStoreId())
                        .eq(PickDtl::getAreaId, putDtl.getAreaId())
                        .eq(PickDtl::getLocatorId, putDtl.getLocatorId())
                        .eq(PickDtl::getPno, putDtl.getPno())
                );
                //存在挑拣任务，对挑拣任务进行处理
                if (dtls != null && dtls.size() > 0) {
                    for (PickDtl dtl : dtls) {
                        Pick update = baseMapper.selectById(dtl.getPickId());
                        //生成库存
                        InventoryBo inBo = new InventoryBo();
                        inBo.setPickType(update.getPickType());
                        inBo.setStoreId(dtl.getStoreId());
                        inBo.setAreaId(dtl.getAreaId());
                        inBo.setLocatorId(dtl.getLocatorId());
                        inBo.setPno(dtl.getPno());
                        inBo.setName(dtl.getName());
                        inBo.setNums(dtl.getNums());
                        inBo.setDeptId(update.getDeptId());
                        inBo.setPics(dtl.getPics());
                        inBo.setDelFlag("0");
                        inBo.setTaskId(update.getId());
                        inBo.setMark("1");
                        iInventoryService.addInventory(inBo);

                        //生成仓库日志  0-入库；1-出库 2-处置 3-上架 4-挑拣 5-看样
                        StoreLogBo logBo = new StoreLogBo();
                        logBo.setDeptId(update.getDeptId());
                        logBo.setStoreId(dtl.getStoreId());
                        logBo.setLogTime(new Date());
                        if (LoginHelper.checkLoginUser()) {
                            logBo.setUserId(LoginHelper.getUserId());
                            logBo.setOperator(LoginHelper.getUsername());
                        } else {
                            logBo.setOperator("智能柜推送");
                        }

                        logBo.setLogType("4");
                        logBo.setDelFlag("0");
                        logBo.setContent(JsonUtils.toJsonString(data));
                        iStoreLogService.insertByBo(logBo);

                        PropertyLog propertyLog = saveLog(dtl, update.getId(), update.getDeptId(), update.getStoreId(), "挑拣出柜");
                        propertyLogMapper.insert(propertyLog);
                        PropertyLogModelsVo pushData = new PropertyLogModelsVo();
                        pushData.setApi("proBase");
                        pushData.setData(propertyLogMapper.selectPropertyLogVoByID(propertyLog.getId()));
                        PushDatasUtil.pushPropertyDatas(pushData);

                        //完成挑拣
                        dtl.setStatus("1");
                        pickDtlMapper.insertOrUpdate(dtl);

                        //更新库位
                        if (data.getCabinetAisleRelaId() == null) {
                            CabinetGroup group = cabinetGroupMapper.selectOne(new LambdaQueryWrapper<CabinetGroup>().eq(CabinetGroup::getSnNumber, data.getSmartCabinetId()));
                            if (group == null) {
                                return false;
                            }
                            Locator locator = locatorMapper.selectOne(new LambdaQueryWrapper<Locator>()
                                    .eq(Locator::getCabinetAisleRelaId, data.getCabinetAisleRelaId())
                                    .eq(Locator::getCabinetGroupId, group.getId())
                            );
                            if (locator != null) {
                                //更新库位数量
                                locator.setPnums(locator.getPnums() == null ? 0 : locator.getPnums() - 1);
                                //更新库位状态
                                if (StringUtils.isNotBlank(locator.getStatus()) && "2".equals(locator.getStatus())) {
                                    locator.setStatus("1");
                                }
                                //更新柜号数量（+）
                                locatorMapper.updateById(locator);
                            }
                            group.setPnums(group.getPnums() == null ? 0 : group.getPnums() - 1);
                        }
                        //判断上架任务单的上架任务是否已完成
                        Long unPick = pickDtlMapper.selectCount(new LambdaQueryWrapper<PickDtl>()
                                .eq(PickDtl::getPickId, dtl.getPickId())
                                .eq(PickDtl::getStatus, "0")
                        );
                        if (unPick == null || unPick == 0) {
                            update.setStatus("1");
                            update.setFinishTime(new Date(data.getOutSmartCabinetTime()));
                        }
                        flag = baseMapper.updateById(update) > 0;
                    }
                } else {
                    //记录日志
                    PutTask update = putTaskMapper.selectById(putDtl.getTaskId());
                    PickDtl pickDtl = BeanUtil.toBean(putDtl, PickDtl.class);
                    PropertyLog propertyLog = saveLog(pickDtl, update.getId(), update.getDeptId(), putDtl.getStoreId(), "出柜");
                    propertyLogMapper.insert(propertyLog);
                    PropertyLogModelsVo pushData = new PropertyLogModelsVo();
                    pushData.setApi("proBase");
                    pushData.setData(propertyLogMapper.selectPropertyLogVoByID(propertyLog.getId()));
                    PushDatasUtil.pushPropertyDatas(pushData);
                }
            }
        }
        return flag;
    }

    @Override
    public void pushPickDatas(String id) {

    }

    @Override
    public List<PickDtlVo> deleteWithBoxByIds(String boxId, String id) {

        List<PickDtl> pickDtls = pickDtlMapper.selectList(new LambdaQueryWrapper<PickDtl>().eq(PickDtl::getPickId, id));
        //移除上架明细中的箱子
        if (pickDtls != null && pickDtls.size() > 0) {
            pickDtls.stream().forEach(item -> {
                if (item.getBoxId().equals(boxId)) {
                    item.setBoxId(null);
                    item.setBoxNo(null);
                }
            });
            Box box = boxMapper.selectById(boxId);
            if (box != null) {
                box.setStatus("0");//设置为待使用
                boxMapper.updateById(box);
            }
        }
        pickDtlMapper.updateBatchById(pickDtls);

        List<PickDtlVo> pickDtlVos = pickDtls.stream().map(item -> {
            PickDtlVo vo = new PickDtlVo();
            BeanUtil.copyProperties(item, vo);
            vo.setStoreName(storeMapper.selectVoById(vo.getStoreId()).getName());
            vo.setAreaName(areaMapper.selectVoById(vo.getAreaId()).getName());
            vo.setLocatorName(locatorMapper.selectVoById(vo.getLocatorId()).getName());

            return vo;
        }).collect(Collectors.toList());
        return pickDtlVos;
    }

    @Override
    public List<SmartCabinetPickProVo> getSmartCabinetPickPro(String smartCabinetId) {

        return pickDtlMapper.getSmartCabinetPickPro(smartCabinetId);
    }

    @Override
    public TableDataInfo<OutboundHandoverBo> getOutboundHandoverList(PageQuery pageQuery, OutboundHandoverBo bo) {

        String beginTime = (String) bo.getParams().get("beginCreateTime");
        String endTime = (String) bo.getParams().get("endCreateTime");
        Wrapper<Object> queryWrapper = new QueryWrapper<>().func(i -> {
            if (StrUtil.isNotBlank(bo.getIsSign())) {
                if ("0".equals(bo.getIsSign())) {
                    i.eq("w.is_sign", '0');
                } else {
                    i.and(r -> r.isNull("w.is_sign").or().eq("w.is_sign", "1"));
                }
            }
            if (StrUtil.isNotBlank(bo.getIsSign())) {
                if ("0".equals(bo.getIsSign())) {
                    i.eq("w.is_sign", '0');
                } else {
                    i.and(r -> r.isNull("w.is_sign").or().eq("w.is_sign", "1"));
                }
            }
            if (StrUtil.isNotBlank(bo.getEvidence())) {
                if ("1".equals(bo.getEvidence())) {
                    i.eq("t.evidence", '1');
                } else {
                    i.and(r -> r.isNull("t.evidence").or().eq("t.evidence", "0"));
                }
            }
            i.eq(StrUtil.isNotBlank(bo.getType()), "t.type", bo.getType());
//            i.exists(StrUtil.isNotBlank(bo.getPno()),
//                    StrUtil.format("select 1 from t_pick_dtl where p.id = pick_id and del_flag = 0 and pno ='{}'", bo.getPno()));
            i.and(StrUtil.isNotBlank(bo.getPno()),wrapper -> wrapper.exists(
                StrUtil.format("select 1 from t_pick_dtl where p.id = pick_id and del_flag = 0 and pno ='{}'", bo.getPno())).or().like("t.task_no",bo.getPno()));
            i.like(StrUtil.isNotBlank(bo.getTaskNo()), "t.task_no", bo.getTaskNo());
            i.eq(StrUtil.isNotBlank(bo.getRegion()) && !"QB".equals(bo.getRegion()), "d.region", bo.getRegion());
            i.between(beginTime != null && endTime != null, "p.finish_time", beginTime, endTime);
        });


        return TableDataInfo.build(baseMapper.getOutboundHandoverList(pageQuery.build(), queryWrapper));
    }

    public String getNo() {

        LambdaQueryWrapper<Pick> lqw = Wrappers.lambdaQuery();
        Long maxNumObject = baseMapper.selectCount(lqw);
        String num = "";
        String todayStr = DateUtils.date2String(new Date(), "yyMMdd");

        if (maxNumObject == null) {
            num = todayStr + "000001";
        } else {
            String maxnumStr = "00000" + maxNumObject.toString();
            String maxnumNo = maxnumStr.substring(maxnumStr.length() - 6, maxnumStr.length());
            String nextnumNo = StringUtils.nextNo(maxnumNo, 6);
            num = todayStr + nextnumNo;
        }
        return num;
    }

    //日志添加
    public void addOperatorLog(String objid, String type, String content) {

        OperatorLog log = new OperatorLog();
        log.setId(IdUtil.simpleUUID());
        log.setObjid(objid);
        log.setDelFlag("0");
        log.setLogTime(new Date());
        log.setUserId(LoginHelper.getUserId());
        log.setOperator(LoginHelper.getNickname());
        log.setLogType(type);
        log.setContent(content);
        logMapper.insert(log);
    }

    //财物日志添加
    private PropertyLog saveLog(PickDtl dtl, String objid, Long deptId, String storeId, String content) {

        PropertyLog propertyLog = new PropertyLog();

        BeanUtil.copyProperties(dtl, propertyLog, "id");
        propertyLog.setId(IdUtil.simpleUUID());
        propertyLog.setObjid(objid);
        propertyLog.setLogTime(new Date());
        propertyLog.setLogType(PropertyLogType.PICK.getCode());//0-移交登记 1-入库 2-出库 3-调用 4-处置 5-交接 6-上架 7-挑拣
        propertyLog.setContent(content);
        propertyLog.setReceiveDept(deptId);
        if (LoginHelper.checkLoginUser()) {
            propertyLog.setUserId(LoginHelper.getUserId());
            propertyLog.setOperator(LoginHelper.getNickname());
            SysDept dept = deptMapper.selectById(LoginHelper.getDeptId());
            propertyLog.setNode(PropertyLogNode.getNodeCodeByBuss(dept.getLevel(), "7"));
        } else {
            propertyLog.setOperator("--");
            propertyLog.setNode(PropertyLogNode.getNodeCodeByBuss(3l, "7"));
        }
        propertyLog.setInfo(JsonUtils.toJsonString(dtl));
        propertyLog.setDelFlag("0");
        propertyLog.setStoreId(storeId);


//        propertyLogMapper.insert(propertyLog);
        return propertyLog;
    }

}
